"""
金融监控系统后端服务
使用 FastAPI 框架
"""
from logging import Logger


import logging
import time
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.api.v1.routes import api_router
from app.core.exceptions import (
    app_exception_handler,
    http_exception_handler,
    general_exception_handler,
    AppException
)
from app.core.performance_monitor import PerformanceMonitorMiddleware
from fastapi import HTTPException
from starlette.concurrency import iterate_in_threadpool
import json

# 初始化日志
from app.core.logging_config import setup_logging
setup_logging()

# 获取日志记录器
logger = logging.getLogger(__name__)

# 禁用watchfiles.main的日志输出
logging.getLogger("watchfiles.main").setLevel(logging.CRITICAL)

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    description=settings.APP_DESCRIPTION,
    version=settings.APP_VERSION
)

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 性能监控中间件
app.add_middleware(
    PerformanceMonitorMiddleware,
    exclude_paths=["/health", "/"]
)

# 注册异常处理器
app.add_exception_handler(AppException, app_exception_handler)  # type: ignore
app.add_exception_handler(HTTPException, http_exception_handler)  # type: ignore
app.add_exception_handler(Exception, general_exception_handler)  # type: ignore

# 包含API路由
app.include_router(api_router, prefix=settings.API_PREFIX)

# 数据库初始化
@app.on_event("startup")
async def startup_event():
    """应用启动时初始化数据库"""
    logger.info("开始初始化数据库")
    try:
        from app.core.init_db import init_db
        init_db()
        logger.info("数据库初始化成功")
    except Exception as e:
        logger.error(f"数据库初始化失败: {e}")
        raise
    
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时执行清理工作"""
    logger.info("应用正在关闭，执行清理工作")

# 健康检查端点
@app.get("/health")
async def health_check():
    """健康检查端点，用于监控服务状态"""
    logger.info("健康检查接口被调用")
    from datetime import datetime
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "service": "monitor-backend"
    }

@app.get("/")
async def root():
    """根路径，返回API基本信息"""
    logger.info("根路径接口被调用")
    return {
        "message": "金融监控系统API",
        "version": "1.0.0",
        "docs": "/docs"
    }

if __name__ == "__main__":
    import uvicorn
    import os
    logger.info("启动应用服务器")
    
    # 配置Uvicorn参数
    uvicorn_args = {
        "app": "app.main:app",
        "host": settings.HOST,
        "port": settings.PORT,
        "log_level": settings.LOG_LEVEL
    }
    
    # 如果启用了调试模式，则配置文件监视
    if settings.DEBUG:
        uvicorn_args["reload"] = True
        # 设置重载延迟以减少频繁重启
        uvicorn_args["reload_delay"] = 3.0
        # 排除不需要监视的目录和文件
        uvicorn_args["reload_excludes"] = [
            "logs/*",
            "logs/**/*",
            "*.log",
            "tmp/*",
            ".git/*",
            ".git/**/*",
            "__pycache__/*",
            "__pycache__/**/*",
            "*.pyc",
            "*.pyo",
            "*~",
            ".DS_Store"
        ]
        # 明确指定需要监视的目录
        uvicorn_args["reload_dirs"] = ["app/"]
    
    uvicorn.run(**uvicorn_args)